# coding: utf-8

import logging

from common import orm
from common.account.model.account import Account
from common.stats import MG_BIGBANG_COLL as mg
from common.utils.decorator import mongo_wrapper, sql_wrapper

_LOGGER = logging.getLogger(__name__)


@mongo_wrapper
def calc_first_award(user_id, amount):
    # 新首充活动
    amount = float(amount)
    award = 0
    if get_first_award(user_id):
        return award
    if 50 <= amount < 100:
        award = 2
    elif 100 <= amount < 200:
        award = 4
    elif 200 <= amount < 500:
        award = 8
    elif 500 <= amount < 1000:
        award = 18
    elif 1000 <= amount < 2000:
        award = 38
    elif 2000 <= amount < 5000:
        award = 88
    elif 5000 <= amount < 50000:
        award = 188
    elif amount >= 50000:
        award = 1888
    if not award:
        return award
    add_award_to_user(user_id, award)
    _LOGGER.info('user-{} took part in 188recharge_campaign'.format(user_id))
    return award


@mongo_wrapper
def get_first_award(user_id):
    user_info = mg.user_stats.find_one({'_id': user_id})
    recharge_count = user_info.get('recharge')['count'] if user_info.get('recharge') else 0
    return True if recharge_count > 0 else False


@mongo_wrapper
def get_fresh_award(user_id, fresh_type='fresh_award'):
    # 新手活动
    user_info = mg.user_stats.find_one({'_id': user_id})
    if not user_info:
        return False
    return True if user_info.get(fresh_type) else False


@mongo_wrapper
def set_fresh_award(user_id, fresh_type='fresh_award'):
    mg.user_stats.update_one({'_id': user_id}, {'$set': {fresh_type: 1}}, True)


@sql_wrapper
def add_award_to_user(user_id, amount):
    account = Account.query.filter(Account.id == user_id).with_for_update().first()
    account.balance = float(account.balance) + float(amount)
    account.save(auto_commit=False)

    orm.session.commit()
    return True